<?php

namespace common\behavior\CommonMessagePushing;

use common\model\ProjectStepCategoryConfirmConfigModel;
use common\model\ReviewFeedbackConfirmModel;
use common\model\ReviewFeedbackModel;
use common\service\DemandOrderService;
use common\service\ProjectService;
use Webman\Stomp\Client;

/**
 * 需求单发布 消息通知
 */
class DemandOrderPublishBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        $demandOrder = model(ReviewFeedbackModel::class)->find($params['demand_order_id']);
        if (empty($demandOrder) || ($demandOrder['demand_type'] !== 'demand_order')) {
            return;
        }
        $pf = DemandOrderService::getInstance()->isAllPublished($params['demand_order_id']);
        if (!$pf) {
            return;
        }
        $demandOrder['step_category_ids'] = split_array($params['step_category_id'] ?? $demandOrder['step_category_ids']);
        $receiver = $params['receiver'] ?? [];
        $receiverCc = $params['receiver_cc'] ?? [];
        if (empty($receiver)) {
            // 确认人员通知
            $userConfirmed = model(ReviewFeedbackConfirmModel::class)
                ->where(['review_feedback_id' => $demandOrder['id']])
                ->column('user_id');
            $userList = $userConfirmed;
            // 按需填充未确认的默认人员
            if ($params['notice_all'] ?? false) {
                $where = [
                    'project_id' => $demandOrder['project_id'],
                    'step_category_id' => ['in', implode(',', $demandOrder['step_category_ids'])],
                    'type' => 'demand_order_confirm',
                ];
                $defaultConfirmUser = model(ProjectStepCategoryConfirmConfigModel::class)
                    ->where($where)
                    ->column('confirm_user_id');
                array_push($userList, ...$defaultConfirmUser);
            }
            // 区分确认人、未确认人
            $receiver = array_map(fn($user) => [
                'user_id' => $user,
                'role' => in_array($user, $userConfirmed) ? 'confirm_user' : 'not_confirm_user'
            ], $userList);
            $receiver = array_merge($receiver, [
                ['user_id' => $demandOrder['created_by'], 'role' => 'created_by'],
                ['user_id' => $demandOrder['proposer'], 'role' => 'proposer'],
            ]);
        }
        // 抄送
        if (empty($receiver)) {
            $projectReceiverConfig = ProjectService::getInstance()->projectConfigMessageReceiverFind([
                'project_id' => $demandOrder['project_id'],
                'step_category_id' => $demandOrder['step_category_ids'],
                'role_code_list' => [
                    'producer',
                    'headman'
                ]
            ]);
            $projectReceiverConfig = array_merge(...array_column($projectReceiverConfig, 'message_receiver_list', 'id'));
            foreach ($projectReceiverConfig as $userGroup) {
                foreach ($userGroup['user_list'] as $user) {
                    $receiverCc[] = [
                        'role' => $userGroup['role'],
                        'user_id' => $user,
                    ];
                }
            }
        }
        $data = [
            'source_user_id' => $demandOrder['created_by'],
            'time' => $demandOrder['created'],
            'source_id' => $demandOrder['id'],
            'source_module_code' => 'demand_order',
            'category' => 'demand_order_publish',
            'receiver' => $receiver,
            'receiver_cc' => $receiverCc,
        ];
        try {
            trace("common demand order publish push behavior" . request()->getUnionUserId(), 'DEBUG');
            Client::send('common_message_pushing', build_queue_data_with_xu($data));
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
        return;
    }
}
